package com.party.mobile.web.controller.mall;

import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.mall.MallProduct;
import com.party.core.model.mall.MallShoppingCart;
import com.party.core.model.mall.MallShoppingCartOutput;
import com.party.core.model.mall.MallStore;
import com.party.core.model.system.TargetType;
import com.party.core.service.mall.IMallProductService;
import com.party.core.service.mall.IMallShoppingCartService;
import com.party.core.service.mall.IMallStoreService;
import com.party.core.service.member.IMemberGroupService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.mall.MallGoodsBizService;
import com.party.mobile.biz.mall.MallShoppingCartBizService;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: Administrator.
 * @Description: 商城购物车
 * @Date:Created in 2017/8/29 0029 下午 12:02.
 */
@Controller
@Authorization
@RequestMapping(value = "mall/shoppingCart")
public class MallShoppingCartController {
    @Autowired
    private IMallShoppingCartService mallShoppingCartService;
    @Autowired
    private IMallProductService mallProductService;
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private MallShoppingCartBizService mallShoppingCartBizService;
    @Autowired
    private MallGoodsBizService mallGoodsBizService;
    @Autowired
    private IMallStoreService mallStoreService;
    @Autowired
    private IMemberGroupService memberGroupService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 购物车列表
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("list")
    @VisitCollect(module = TargetType.MALL)
    public AjaxResult list(Page page, HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            MallStore mallStore = mallStoreService.getUnique();
            List<MallShoppingCartOutput> mallShoppingCarts = mallShoppingCartBizService.getGoodShoppingCart(currentUser.getId(), page);
            for (MallShoppingCartOutput output : mallShoppingCarts) {
                mallShoppingCartBizService.transfromStoreName(mallStore, output);
            }
            return AjaxResult.success(mallShoppingCarts, page);
        } catch (Exception e) {
            logger.error("购物车列表异常", e);
            return AjaxResult.error(100, "购物车列表异常");
        }
    }

    /**
     * 失效的购物车列表
     *
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("badList")
    public AjaxResult badList(Page page, HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            List<MallShoppingCartOutput> mallShoppingCarts = mallShoppingCartBizService.getBadShoppingCart(currentUser.getId(), page);
            return AjaxResult.success(mallShoppingCarts, page);
        } catch (Exception e) {
            logger.error("失效的购物车列表", e);
            return AjaxResult.error(100, "失效的购物车列表");
        }
    }

    /**
     * 加入购物车
     *
     * @param productId     产品id
     * @param quantity      数量
     * @param distributorId 分销者
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addCart", method = RequestMethod.POST)
    public AjaxResult addCart(String productId, Integer quantity, String distributorId, HttpServletRequest request) {
        if (StringUtils.isEmpty(productId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "产品id不能为空");
        }
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            if (null != currentUser.getIsMemberGroup() && YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                distributorId = memberGroupService.getPartnerId(distributorId);
            }

            MallShoppingCart shoppingCart = mallShoppingCartService.getUnique(new MallShoppingCart(currentUser.getId(), productId, distributorId));
            MallProduct mallProduct = mallProductService.get(productId);
            if (shoppingCart == null) {
                shoppingCart = new MallShoppingCart();
                shoppingCart.setMemberId(currentUser.getId());
                shoppingCart.setProductId(productId);
                shoppingCart.setQuantity(quantity);
                shoppingCart.setPrice(mallProduct.getPrice());
                shoppingCart.setDistributorId(distributorId);
                mallShoppingCartService.insert(shoppingCart);
            } else {
                Integer totalQuantity = shoppingCart.getQuantity() + quantity;
                if (totalQuantity > mallProduct.getRealStock()) {
                    totalQuantity = mallProduct.getRealStock().intValue();
                }
                shoppingCart.setQuantity(totalQuantity);
                mallShoppingCartService.update(shoppingCart);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("加入购物车异常", e);
            return AjaxResult.error(11000, "加入购物车异常");
        }
    }

    /**
     * 更新购物车记录
     *
     * @param mallShoppingCart 购物车记录
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateCart", method = RequestMethod.POST)
    public AjaxResult updateCart(MallShoppingCart mallShoppingCart, HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(mallShoppingCart.getId())) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "购物车记录id不能为空");
            }
            MallShoppingCart db = mallShoppingCartService.get(mallShoppingCart.getId());
            if (db == null) {
                return AjaxResult.error(110, "该记录不存在");
            }
            db.setQuantity(mallShoppingCart.getQuantity());
            mallShoppingCartService.update(db);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(100, "更新购物车记录异常");
        }
    }

    /**
     * 删除购物车商品
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleteCart", method = RequestMethod.POST)
    public AjaxResult deleteCart(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }
        try {
            for (String id : ids.split(",")) {
                mallShoppingCartService.delete(id);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除购物车记录异常", e);
            return AjaxResult.error(100, "删除购物车记录异常");
        }
    }

    /**
     * 获取购物车数字
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getCount", method = RequestMethod.GET)
    public AjaxResult getCount(HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            List<MallShoppingCartOutput> mallShoppingCarts = mallShoppingCartBizService.getGoodShoppingCart(currentUser.getId(), null);
            return AjaxResult.success(mallShoppingCarts.size());
        } catch (Exception e) {
            logger.error("获取购物车数字异常", e);
            return AjaxResult.error(100, "获取购物车数字异常");
        }
    }

    /**
     * 清空购物车失效商品
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "clearBad", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult clearBad(HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            List<MallShoppingCartOutput> mallShoppingCarts = mallShoppingCartBizService.getBadShoppingCart(currentUser.getId(), null);
            for (MallShoppingCartOutput output : mallShoppingCarts) {
                mallShoppingCartService.delete(output.getId());
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("清空购物车失效商品异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "清空购物车失效商品异常");
        }
    }


    /**
     * 购物车失效商品加入收藏
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "badAddFavorite", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult badAddFavorite(HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            List<MallShoppingCartOutput> mallShoppingCarts = mallShoppingCartBizService.getBadShoppingCart(currentUser.getId(), null);
            for (MallShoppingCartOutput output : mallShoppingCarts) {
                try {
                    mallGoodsBizService.addFavorite(currentUser.getId(), output.getGoodsId());
                } catch (BusinessException e) {
                    continue;
                } catch (Exception e) {
                    throw new Exception(e);
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("购物车失效商品加入收藏异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "购物车失效商品加入收藏异常");
        }
    }
}
